<template>
  <view class="content">
    <u-navbar :title="isEdit ? '编辑产品' : '新增产品'" :border="false" :autoBack="true"></u-navbar>
    
    <view class="form-container">
      <u-form :model="form" ref="uForm" :labelWidth="140">
        <u-form-item label="产品名称" prop="name" :required="true">
          <u-input v-model="form.name" placeholder="请输入产品名称" />
        </u-form-item>
        
        <u-form-item label="产品分类" prop="categoryId" :required="true">
          <u-select v-model="form.categoryId" :list="categoryList" @confirm="selectCategory"></u-select>
        </u-form-item>
        
        <u-form-item label="产品编号" prop="code">
          <u-input v-model="form.code" placeholder="请输入产品编号" />
        </u-form-item>
        
        <u-form-item label="产品价格" prop="price">
          <u-input v-model="form.price" type="number" placeholder="请输入产品价格" />
        </u-form-item>
        
        <u-form-item label="产品图片" prop="image" :required="true">
          <view class="upload-box">
            <u-upload
              :fileList="fileList"
              @afterRead="afterRead"
              @delete="deletePic"
              name="1"
              multiple
              :maxCount="1"
            ></u-upload>
          </view>
        </u-form-item>
        
        <u-form-item label="材质" prop="texture">
          <u-input v-model="form.texture" placeholder="请输入产品材质" />
        </u-form-item>
        
        <u-form-item label="规格说明" prop="scaleDescription">
          <u-input v-model="form.scaleDescription" type="textarea" placeholder="请输入规格说明" />
        </u-form-item>
      </u-form>
      
      <view class="form-actions">
        <u-button type="info" text="取消" @click="goBack"></u-button>
        <u-button type="primary" text="保存" @click="saveProduct"></u-button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isEdit: false,
      productId: null,
      form: {
        name: '',
        categoryId: '',
        code: '',
        price: '',
        image: '',
        texture: '',
        scaleDescription: ''
      },
      fileList: [],
      categoryList: [],
      rules: {
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择产品分类', trigger: 'change' }
        ],
        image: [
          { required: true, message: '请上传产品图片', trigger: 'change' }
        ]
      }
    }
  },
  onLoad(option) {
    if (option.id) {
      this.isEdit = true;
      this.productId = option.id;
    }
    
    this.fetchCategories();
    
    if (this.isEdit) {
      this.fetchProductDetail();
    }
  },
  methods: {
    // 获取产品详情
    fetchProductDetail() {
      uni.showLoading({
        title: '加载中'
      });
      
      this.$api.get(`/api/Product/${this.productId}`)
        .then(res => {
          if (res.data.code === 200) {
            const product = res.data.data;
            this.form = {
              name: product.name,
              categoryId: product.categoryId,
              code: product.code || '',
              price: product.price || '',
              image: product.image || '',
              texture: product.texture || '',
              scaleDescription: product.scaleDescription || ''
            };
            
            // 设置图片
            if (product.image) {
              this.fileList = [{
                url: product.image,
                status: 'success',
                message: '上传成功'
              }];
            }
          } else {
            this.$u.toast(res.data.msg || '获取产品详情失败');
          }
        })
        .catch(err => {
          this.$u.toast('网络异常，请稍后重试');
          console.error(err);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    // 获取分类列表
    fetchCategories() {
      this.$api.get('/api/Category/Tree')
        .then(res => {
          if (res.data.code === 200) {
            let options = [];
            
            res.data.data.forEach(category => {
              options.push({
                value: category.id,
                label: category.name
              });
              
              if (category.children && category.children.length > 0) {
                category.children.forEach(child => {
                  options.push({
                    value: child.id,
                    label: `　${child.name}`
                  });
                });
              }
            });
            
            this.categoryList = options;
          } else {
            this.$u.toast(res.data.msg || '获取分类列表失败');
          }
        })
        .catch(err => {
          this.$u.toast('网络异常，请稍后重试');
          console.error(err);
        });
    },
    
    // 选择分类
    selectCategory(e) {
      this.form.categoryId = e[0].value;
    },
    
    // 上传图片后处理
    afterRead(event) {
      const file = event.file;
      
      uni.showLoading({
        title: '上传中'
      });
      
      // 实际项目中应该调用上传API
      uni.uploadFile({
        url: this.$apiUrl + '/api/File/Upload',
        filePath: file.url,
        name: 'file',
        formData: {
          type: 'product'
        },
        success: uploadRes => {
          const result = JSON.parse(uploadRes.data);
          if (result.code === 200) {
            this.form.image = result.data.url;
          } else {
            this.$u.toast(result.msg || '上传失败');
          }
        },
        fail: () => {
          this.$u.toast('上传失败');
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },
    
    // 删除图片
    deletePic() {
      this.form.image = '';
      this.fileList = [];
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 保存产品
    saveProduct() {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          if (!this.form.image) {
            return this.$u.toast('请上传产品图片');
          }
          
          uni.showLoading({
            title: '保存中'
          });
          
          const apiMethod = this.isEdit ? 'put' : 'post';
          const apiUrl = this.isEdit ? `/api/Product/${this.productId}` : '/api/Product';
          
          this.$api[apiMethod](apiUrl, this.form)
            .then(res => {
              if (res.data.code === 200) {
                this.$u.toast('保存成功');
                setTimeout(() => {
                  uni.navigateBack();
                }, 1500);
              } else {
                this.$u.toast(res.data.msg || '保存失败');
              }
            })
            .catch(err => {
              this.$u.toast('网络异常，请稍后重试');
              console.error(err);
            })
            .finally(() => {
              uni.hideLoading();
            });
        }
      });
    }
  }
}
</script>

<style lang="scss">
.content {
  padding: 20rpx;
  
  .form-container {
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 30rpx;
    
    .upload-box {
      width: 100%;
    }
    
    .form-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 40rpx;
      
      .u-button {
        margin-left: 20rpx;
      }
    }
  }
}
</style> 